package icu.xuyijie.springbootlearning2.chapter6.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 徐一杰
 * @date 2022/10/25 17:18
 * @description security认证成功逻辑，一般用于前后端分离，定义这个以后，security内置的页面跳转就失效了
 */
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        logger.info("登录成功");
        response.setContentType("application/json;charset=UTF-8");

        //这里写你登录成功后的逻辑，返回给前端数据，让前端进行页面跳转
        //用户身份信息
        Object principal = authentication.getPrincipal();
        Map<String, Object> map = new HashMap<>(4);
        map.put("code", 200);
        map.put("message", "登录成功");
        map.put("data", principal);
        ObjectMapper objectMapper = new ObjectMapper();
        String result = objectMapper.writeValueAsString(map);
        response.getWriter().println(result);
    }
}
